'use strict';
const net = require("net"),fs = require('fs'),lAddr = "192.168.0.201",lPort = 8090; 
const loger = require("./module/loger");

process.on('uncaughtException', function(err) {
	loger.info('uncaughtException: ', err.stack);
});

global.client = null;
global.sdObj = {};

function runClient()
{	
	var clientSocket = new net.Socket();
	clientSocket = net.connect(lPort, lAddr, () => {
		loger.info("connect server OK");
		const child_process = require('child_process'),os = require('os');
		let cmd = "ifconfig | grep HWaddr | cut -d ' ' -f 11";
		if(os.platform() == 'win32') cmd = "GETMAC /NH";
		child_process.exec(cmd, (error, stdout, stderr)=>{
			if(error)
			{
				console.log("get mac error", error);
				return;
			}
			global.client = clientSocket;
			let mac = stdout.toString();
			if(os.platform() == 'win32') mac = stdout.substr(2, 17);
			console.log("get mac", mac);
			global.mac = mac;
			let buf = Buffer.allocUnsafe(21);
			buf.writeUInt16LE(21, 0);
			buf.writeUInt16LE(1, 2);
			buf.write(mac, 4);
			clientSocket.write(buf);
		});
	});

	var olddata = null; //旧数据缓存
	clientSocket.on("data", (data) => {
		var runData = {len:0, m:0, json:{}};
		var msg = require(__dirname + "/config/msgconfig");
		if(olddata){
			data = Buffer.concat([data, olddata], data.length + olddata.length);
			olddata = null;
		}

		while(data.length > 0){
			runData.len = data.readUInt16LE(0);
			if(data.length >= runData.len){
				runData.m = data.readUInt16LE(2);
				if(runData.len < 4){
					data = data.slice(runData.len);
					runData.len = 0;
					continue;
				}
				runData.json = data.slice(4, runData.len);
				
				loger.info(runData.m, runData.json);
				if(!("cmds" in global.sdObj)){
					global.sdObj.finish = 1;
					global.sdObj.cmds = [];
				} 
				global.sdObj.cmds.push([runData.m, runData.json]);
				data = data.slice(runData.len);
				runData.len = 0;
			}else{
				olddata = data;
				break;
			}
		}
	});

	clientSocket.on("end", () => {
		loger.info("socket end");
		nw.App.closeAllWindows();
		global.client = null;
	});

	clientSocket.on("error", (err) => {
		loger.info("socket error", err);
		nw.App.closeAllWindows();
		global.client = null;
	});
}

let sn = 0;
setInterval(function()
{
	sn++;
	if(global.client == null){ //关闭
		nw.App.closeAllWindows();
		// if(sn > 1 && sn % 3 == 0){
			// global.sdObj = {};
			// const web = require("./module/web");
			// web.openUrl("");
			// runClient();
		// } 
		return;
	}	
	
	//执行命令
	const msg = require(__dirname + "/config/msgconfig"); //在定时器下面必需是完整目录
	if(global.sdObj.finish && global.sdObj.cmds && global.sdObj.cmds.length > 0){
		if(global.sdObj.end > 0){
			global.sdObj.cmds = [];
			return;
		}
		let od = global.sdObj.cmds.shift();
		let runData = {m:od[0],json:od[1]};
		if(od[0] == 4 && process.memoryUsage().rss > 786000000){ //内存太高了强制结束
			nw.App.closeAllWindows();
			return;
		}
		if(runData.m in msg){
			let filestr = msg[runData.m];
			let _run = function (runData, c){
				var udata = {m:runData.m, json:runData.json};
				return function(){
					var runObj;
					runObj = require(__dirname + "/" + filestr);
					global.sdObj.finish = 0;
					global.sdObj.runt = new Date().getTime();
					runObj.run(udata, c);
				}
			}
			_run(runData, global.client)();
			loger.info("runend", od[1].toString());
		}else{
			loger.info('not msg :', runData.m);
		}
	}
	
	//检测命令执行时间
	if(global.sdObj.runt){
		let ltm = new Date().getTime() - global.sdObj.runt;
		if(ltm > 180*1000){
			if(!("end" in global.sdObj)){
				global.sdObj.end = 1031;
			}
			delete global.sdObj.runt;
		}else if(ltm > 1000 && parseInt(ltm/1000)%10 == 0){ //每10秒执行页面加载成功
			loger.info("run loaded 10s");
			const web = require(__dirname + "/module/web");
			if(parseInt(ltm/1000)%90 == 0) web.reload();
			else web.exeload();
		}		
	}

	
	if(sn > 60){
		sn = 0;
		loger.info("heart");
		//发生心跳
		let h = "heart", buf = Buffer.allocUnsafe(h.length + 4);
		buf.writeUInt16LE(h.length + 4, 0);
		buf.writeUInt16LE(7, 2);
		buf.write(h, 4);
		global.client.write(buf);
	}
	if(global.sdObj.tmp){
		if(global.sdObj.tmp == -1) return;
		const ftp = require(__dirname + "/module/ftp");
		global.sdObj.tmp = -1;
		ftp.upfile("tmp.png", '192.168.0.201', "/screenShot/"+global.mac.replace(/-/g,"")+".png", ()=>{delete global.sdObj.tmp;});
		loger.info("uptemp img");
		return;
	}
	if(global.sdObj.err){
		if(global.sdObj.err == -1) return;
		const ftp = require(__dirname + "/module/ftp");
		global.sdObj.err = -1;
		ftp.upfile("err.png", '192.168.0.200', "/error/"+global.mac.replace(/-/g,"")+"_"+global.sdObj.end+"_"+(new Date().getTime())+".png", ()=>{delete global.sdObj.err;});
		loger.info("uptemp err");
		return;
	}
	if("end" in global.sdObj){
		loger.info("send 6 ", global.sdObj.end);
		global.sdObj.finish = 1;
		let buf = Buffer.allocUnsafe(6);
		buf.writeUInt16LE(6, 0);
		buf.writeUInt16LE(6, 2);
		buf.writeInt16LE(global.sdObj.end, 4);
		global.client.write(buf); 
		delete global.sdObj.end;
		delete global.sdObj.runt;
		const web = require(__dirname + "/module/web");
		web.clload();
	}
}, 1000);

runClient();